package com.phuc.game.andPuzzle;

import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.phuc.game.andPuzzle.moreGame.Item;
import com.phuc.game.andPuzzle.moreGame.LazyAdapter;

@SuppressLint("NewApi")
public class MoreGameActivity extends Activity implements OnItemClickListener {
	GridView gridView;
	LazyAdapter adapter;
	private static String URL = "https://mdroid-team.googlecode.com/svn/trunk/data/list_app_hotgirl_puzzle.xml";
	private static String APP = "app";
	private static String APP_NAME = "appname";
	private static String IMAGE_LINK = "imagelink";
	private static String APP_LINK = "link";
	private static String IS_HOT = "ishot";

	private String DEFAULT = "Game bai;Tank";

	private String listAppName = null;
	
	SharedPreferences.Editor editor;

	private ArrayList<Item> list;

	private ArrayList<String> appNamePrefs;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initImageLoader(this);
		
		setContentView(R.layout.more_game);
		SharedPreferences pref = getPreferences(MODE_PRIVATE);
		Log.d("Chung", "phucphuc onCreate");
		editor = pref.edit();
		StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
				.permitAll().build();
		StrictMode.setThreadPolicy(policy);
		TextView tv = (TextView) findViewById(R.id.tv);
		Typeface tf = Typeface.createFromAsset(getAssets(),
				"fonts/victoria.ttf");
		tv.setTypeface(tf);
		gridView = (GridView) findViewById(R.id.gridView1);
		
		list = new ArrayList<Item>();
		
		//NetWorkOn parse xml from svn
		if (isNetworkOnline()) {
			Log.d("Chung", "PhucPhuc NetWork ON");
			list = syncAppList();
			adapter = new LazyAdapter(this, list);
		//NetWork OFF get from SharedPreference
		}else {
			Log.d("Chung", "PhucPhuc NetWork OFF");
			Toast.makeText(getApplicationContext(), "Cần kết nối internet", Toast.LENGTH_LONG).show();
			appNamePrefs = new ArrayList<String>(Arrays.asList(pref.getString(
					APP_NAME, DEFAULT).split(";")));
			for (int i = 0; i < appNamePrefs.size(); i++) {
				Item item = new Item();
				item.setNameApp(appNamePrefs.get(i));
				list.add(item);
			}
			adapter = new LazyAdapter(this, list);
		}
		gridView.setAdapter(adapter);
		gridView.setOnItemClickListener(this);
		Log.d("Chung", "phucphuc Finish");
	}
	
	public static void initImageLoader(Context context) {
		// This configuration tuning is custom. You can tune every option, you may tune some of them,
		// or you can create default configuration by
		//  ImageLoaderConfiguration.createDefault(this);
		// method.
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
				.threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new Md5FileNameGenerator())
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.writeDebugLogs() // Remove for release app
				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
	}
	
	public ArrayList<Item> syncAppList() {
		ArrayList<Item> list = new ArrayList<Item>();
		try {
			XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
			factory.setNamespaceAware(true);
			XmlPullParser parser = factory.newPullParser();
			parser.setInput(new InputStreamReader(new URL(URL).openStream()));
			 
			String name = null;
			Item app = null;
			listAppName = "";
			boolean isApp = false;
			while (parser.getEventType() != XmlPullParser.END_DOCUMENT) {
				int next;
				next = parser.next();

				switch (next) {
				case XmlPullParser.START_TAG:
					name = parser.getName();
					if (TextUtils.equals(APP, name)) {
						isApp = true;
						app = new Item();
					} else if (TextUtils.equals(APP_NAME, name) && isApp) {
						String text = parser.nextText();
						app.setNameApp(text);
						listAppName = listAppName + text + ";";
					} else if (TextUtils.equals(IMAGE_LINK, name) && isApp) {
						app.setLinkImage(parser.nextText());
					} else if (TextUtils.equals(APP_LINK, name) && isApp) {
						app.setLinkApp(parser.nextText());
					} else if (TextUtils.equals(IS_HOT, name) && isApp) {
						app.setIsHot(parser.nextText());
					}
					break;
				case XmlPullParser.END_TAG:
					name = parser.getName();
					if (TextUtils.equals(APP, name)) {
						list.add(app);
					}
					break;

				default:
					break;
				}
			}
			listAppName = listAppName.substring(0,
					listAppName.length() - 1);
			isApp = false;
			Log.d("Chung","End tag:" + listAppName);
			editor.putString(APP_NAME, listAppName);
			editor.commit();
			return list;
		} catch (Exception e) {
			Log.d("Chung", "null:" + e.getMessage());
			return new ArrayList<Item>();
		}
	}

	@Override
	public void onDestroy() {
//		adapter.imageLoader.clearCache();
//		adapter.notifyDataSetChanged();
//		adapter.imageLoader.stopThread();
		gridView.setAdapter(null);
		super.onDestroy();
	}

	public boolean isNetworkOnline() {
		try {
			ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo netInfo = cm.getNetworkInfo(0);
			if (netInfo == null) {
				return false;
			} else {
				return true;
			}
		} catch (Exception e) {
			return false;
		}
	}

	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		if (!isNetworkOnline()) {
			Toast.makeText(this, "Cần kết nối internet", Toast.LENGTH_SHORT).show();
			return;
		}
		Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(list.get(arg2).getLinkApp()));
		startActivity(i);
	}
	
	@Override
	public void onBackPressed() { }
	
	public void onQuit(View view) {
		super.onBackPressed();
		android.os.Process.killProcess( android.os.Process.myPid() );
	}
}
